package csc.daonjpa.java.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import csc.daonjpa.java.domain.Customer;

@Service
public class CustomerDAOImpl implements CustomerDAO {

	@PersistenceContext
	private EntityManager entityManager;
	
	@Transactional
	public List<Customer> getCustomers() {
		List<Customer> customers = null;
		TypedQuery<Customer> query = entityManager.createQuery("Select a from Customer a", Customer.class);
		customers = query.getResultList();
		return customers;
	}

	@Transactional
	public boolean addCustomer(Customer customer) {
		try {
			entityManager.persist(customer);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Transactional
	public Customer getCustomer(String loginId) {
		Query query = entityManager.createQuery("Select c from Customer c Where c.loginId = :lg", Customer.class);
		query.setParameter("lg", loginId);
		Customer customer = (Customer) query.getSingleResult();
		return customer;
	}

	@Transactional
	public boolean updateCustomer(Customer customer) {
		try {
			entityManager.merge(customer);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
